/*
 * Copyright 2021-2022 Open Kunlun Technology <https://www.openkunlun.io>
 */

package io.openkunlun.scalarpc.codegen.model

import scala.meta._

case class AnnotEx private (meta: AnnotEx.Meta) extends CodeEx with CodeEx.Name[AnnotEx] {
  override def tree: Tree = Mod.Annot(Init(meta.tpe, meta.name, meta.argss.map(_.toList).toList))
  override def name: String = meta.tpe match {
    case n: Type.Name => n.value
    case a: Type.Apply => a.tpe match {
      case n: Type.Name => n.value
    }
  }
  override def withName(name: String): AnnotEx = copy(meta = meta.copy(tpe = Type.Name(name)))

  def args: Seq[Any] = {
    meta.argss.flatMap(it => it.collect {
      case lit: Lit => lit.value
    })
  }
  def kwargs: Map[String, Any] = {
    meta.argss
      .flatMap(it => it.collect {
        case Term.Assign(name: Term.Name, lit: Lit) => name.value -> lit.value
      })
      .toMap
  }

  def stringArgs: Seq[String] = {
    meta.argss.flatMap(it => it.collect {
      case lit: Lit.String => lit.value
    })
  }
  def stringKwargs: Map[String, String] = {
    meta.argss
      .flatMap(it => it.collect {
        case Term.Assign(name: Term.Name, lit: Lit.String) => name.value -> lit.value
      })
      .toMap
  }
}
object AnnotEx {
  case class Meta(tpe: scala.meta.Type, name: scala.meta.Name, argss: Seq[Seq[scala.meta.Term]])
}
